# Project variables
BINARY_NAME    := uos-libvirtd-exporter
VERSION        ?= $(shell grep "^Version:" uos-libvirtd-exporter.spec | awk '{print $$2}')
GIT_COMMIT     ?= $(shell git rev-parse --short HEAD)
GIT_DIRTY      ?= $(shell test -n "`git status --porcelain`" && echo "+CHANGES" || true)
BUILD_TIME     ?= $(shell date -u +"%Y-%m-%dT%H:%M:%SZ")

# Go parameters
GOCMD          := go
GOBUILD        := $(GOCMD) build
GOCLEAN        := $(GOCMD) clean
GOTEST         := $(GOCMD) test
GOGET          := $(GOCMD) get
GOMOD          := $(GOCMD) mod
GOFMT          := gofmt
GOVET          := $(GOCMD) vet

# Build flags
LDFLAGS        := -ldflags "-X gitee.com/openeuler/uos-libvirtd-exporter/version.Version=$(VERSION) -X gitee.com/openeuler/uos-libvirtd-exporter/version.Commit=$(GIT_COMMIT) -X gitee.com/openeuler/uos-libvirtd-exporter/version.BuildTime=$(BUILD_TIME) -s -w"

# Directories
DIST_DIR       := dist
BIN_DIR        := bin


.PHONY: all build clean test fmt lint vet run help deps dev-setup build-linux build-arm64 \
		docker-build docker-run docker-clean release-tarball rpm install uninstall \
		check-version check-env sec

.DEFAULT_GOAL  := help

# Display help information
help: ## Show this help message
	@echo "Usage: make [target]"
	@echo ""
	@echo "Targets:"
	@awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {printf "  %-20s %s\n", $$1, $$2}' $(MAKEFILE_LIST)

all: check-env fmt vet test build ## Run all checks and build

# Check environment
check-env: ## Check build environment
	@echo "Checking environment..."
	@if ! go version >/dev/null 2>&1 ; then \
		echo "Error: Go is not installed" ; \
		exit 1 ; \
	fi
	@echo "Go version: $$(go version)"

check-version: ## Display version information
	@echo "Version: $(VERSION)$(GIT_DIRTY)"
	@echo "Git commit: $(GIT_COMMIT)"

# Build targets
build: check-env ## Build the binary
	@echo "Building $(BINARY_NAME)..."
	$(GOBUILD) $(LDFLAGS) -o $(BINARY_NAME) -v

clean: ## Clean build artifacts
	@echo "Cleaning build artifacts..."
	$(GOCLEAN)
	rm -f $(BINARY_NAME) $(BINARY_NAME)-* $(BINARY_NAME)-*.tar.gz
	rm -rf $(DIST_DIR) $(BIN_DIR)

# Test targets
test: check-env ## Run tests
	@echo "Running tests..."
	$(GOTEST) -v ./...

fmt: ## Format code
	@echo "Formatting code..."
	$(GOFMT) -s -w .

lint: ## Run linter (requires golangci-lint)
	@echo "Running linter..."
	golangci-lint run

vet: ## Run go vet
	@echo "Running go vet..."
	$(GOVET) ./...

# Dependency management
deps: ## Download dependencies
	@echo "Downloading dependencies..."
	$(GOMOD) download
	$(GOMOD) tidy

# Development setup
dev-setup: ## Setup development environment (install dependencies)
	@echo "Setting up development environment..."
	$(GOGET) -u golang.org/x/tools/cmd/goimports
	$(GOGET) -u github.com/golangci/golangci-lint/cmd/golangci-lint
	$(GOGET) -u github.com/securego/gosec/cmd/gosec
	@echo "Development setup complete."

# Run the application
run: build ## Run the exporter (requires libvirt)
	@echo "Running $(BINARY_NAME)..."
	./$(BINARY_NAME) --libvirt.uri=qemu:///system

# Cross compilation
build-linux: check-env ## Build for Linux AMD64
	@echo "Cross-compiling for Linux AMD64..."
	GOOS=linux GOARCH=amd64 $(GOBUILD) $(LDFLAGS) -o $(BINARY_NAME)-linux-amd64 -v

build-arm64: check-env ## Build for ARM64
	@echo "Cross-compiling for ARM64..."
	GOOS=linux GOARCH=arm64 $(GOBUILD) $(LDFLAGS) -o $(BINARY_NAME)-linux-arm64 -v

# Docker support
docker-build: ## Build Docker image
	@echo "Building Docker image..."
	docker build -t $(BINARY_NAME):$(VERSION) .
	docker tag $(BINARY_NAME):$(VERSION) $(BINARY_NAME):latest

docker-run: ## Run in Docker container
	@echo "Running in Docker container..."
	docker run -it --rm \
		-v /var/run/libvirt/libvirt-sock:/var/run/libvirt/libvirt-sock \
		-p 9177:9177 \
		--name $(BINARY_NAME) \
		$(BINARY_NAME):latest

docker-clean: ## Clean Docker images
	@echo "Cleaning Docker images..."
	-docker rmi $(BINARY_NAME):$(VERSION) 2>/dev/null || true
	-docker rmi $(BINARY_NAME):latest 2>/dev/null || true

# Release packaging
release-tarball: check-env ## Create release tarballs
	@echo "Creating release tarballs..."
	mkdir -p $(DIST_DIR)
	tar -czvf $(DIST_DIR)/$(BINARY_NAME)-$(VERSION).tar.gz \
		--transform 's|^./|$(BINARY_NAME)-$(VERSION)/|' \
		--exclude=.gitignore \
		--exclude=.git --exclude=.vscode \
		--exclude=*.tar.gz --exclude=*.exe --exclude=*.log \
		--exclude=quickstart --exclude=docs \
		--exclude=$(BINARY_NAME) \
		--exclude=$(BINARY_NAME)-linux-* \
		--exclude=$(DIST_DIR) \
		.
	@echo "Release tarballs created in $(DIST_DIR):"
	@ls -la $(DIST_DIR)/*.tar.gz

# RPM packaging
rpm: release-tarball ## Build RPM package
	@echo "Building RPM package..."
	rpmbuild -ta $(DIST_DIR)/$(BINARY_NAME)-$(VERSION).tar.gz
	@echo "RPM package built."

# Installation
install: build ## Install the binary to /usr/bin
	@echo "Installing $(BINARY_NAME) to /usr/bin..."
	sudo install -d -p -m 0755 /etc/$(BINARY_NAME)
	sudo install -m 0644 config.yaml /etc/$(BINARY_NAME)/
	sudo install -m 0644 uos-libvirtd-exporter.service /usr/lib/systemd/system/
	sudo install -m 0755 $(BINARY_NAME) /usr/bin/
	sudo chmod +x /usr/bin/$(BINARY_NAME)
	@echo "Installation complete."

uninstall: ## Remove the binary from /usr/bin
	@echo "Removing $(BINARY_NAME) from /usr/bin..."
	sudo rm -f /usr/bin/$(BINARY_NAME)
	sudo rm -f /etc/$(BINARY_NAME)/config.yaml
	sudo systemctl stop uos-libvirtd-exporter
	sudo systemctl disable uos-libvirtd-exporter
	sudo rm -f /usr/lib/systemd/system/uos-libvirtd-exporter.service
	sudo systemctl daemon-reload
	sudo rm -rf /etc/$(BINARY_NAME)
	sudo rm -f /var/log/$(BINARY_NAME).log
	@echo "Uninstallation complete."

sec: ## Security audit (requires gosec)
	@echo "Running security audit..."
	gosec ./...
	@echo "Security audit complete."
